<template>
  <div>
    <el-button type="primary" @click="toggleMemberManage" style="margin-bottom: 2vh">成员管理</el-button>
    <member-manage v-if="showMemberManage" :space-id="route.query.id"></member-manage>
    <div v-else>
      <div v-if="editStatusMessage" class="edit-status-message">{{ editStatusMessage }}</div>


      <!-- 禁用编辑时禁用输入框 -->
      <form-create
          v-model="formData"
          :rule="computedRule"
          :option="computedOption"
          @submit="onSubmit"
          @update:modelValue="handleFormChange"
          :disabled="isFormDisabled"
      ></form-create>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from "vue";
import { useRoute } from "vue-router";
import { getFormList, getFormDetail, submitForm } from "@/api/form";
import { ElMessage } from "element-plus";
import MemberManage from "@/components/team/memberManage.vue";
import PdfPreview from "@/components/PdfPreview.vue";

const route = useRoute();
const formList = ref([]);
const currentFormIndex = ref(0);
const formData = ref({});
const isLoaded = ref(false);
const showMemberManage = ref(false);
const pdfPath = ref("");
const editStatusMessage = ref("");
const isFormDisabled = ref(false);  // 用于控制表单禁用状态
let socket = null;

const computedRule = computed(() => {
  if (formList.value.length > 0 && formList.value[currentFormIndex.value]?.rule) {
    return formList.value[currentFormIndex.value].rule;
  }
  return [];
});

const computedOption = computed(() => {
  if (formList.value.length > 0 && formList.value[currentFormIndex.value]?.option) {
    return formList.value[currentFormIndex.value].option;
  }
  return {};
});

const fetchFormList = async (id) => {
  try {
    const res = await getFormList(id);
    if (res.code === 1) {
      const form = res.data;
      formList.value = [
        {
          id: form.id,
          rule: JSON.parse(JSON.parse(form.ruleBuild)),
          option: JSON.parse(JSON.parse(form.optionBuild)),
          createdAt: formatDate(form.createdAt),
          formData: form.formData ? JSON.parse(form.formData) : {},
        },
      ];

      if (formList.value.length > 0) {
        await loadFormData(formList.value[0].id);
      }

      isLoaded.value = true;
    } else {
      ElMessage.error(res.msg || "获取表单数据失败");
    }
  } catch (error) {
    ElMessage.error("获取表单数据失败");
  }
};

const loadFormData = async (formId) => {
  try {
    const res = await getFormDetail(formId);
    if (res.code === 1) {
      formData.value = res.data.formData ? JSON.parse(res.data.formData) : {};
      pdfPath.value = res.data.pdfPath;
    } else {
      ElMessage.error(res.msg || "获取表单数据失败");
    }
  } catch (error) {
    ElMessage.error("获取表单数据失败");
  }
};

const formatDate = (dateArray) => {
  if (!Array.isArray(dateArray)) return "";
  const [year, month, day, hour, minute, second] = dateArray;
  return `${year}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")} ${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}:${second.toString().padStart(2, "0")}`;
};

const onSubmit = async (submittedData) => {
  try {
    const payload = {
      id: formList.value[currentFormIndex.value].id,
      formData: JSON.stringify(submittedData),
      pdfPath: pdfPath.value,
    };

    const res = await submitForm(payload);
    if (res.code === 1) {
      ElMessage.success("表单提交成功");
      await loadFormData(payload.id);
    } else {
      ElMessage.error(res.msg || "表单提交失败");
    }
  } catch (error) {
    ElMessage.error("表单提交失败");
  }
};

const updatePdfPath = (newPath) => {
  pdfPath.value = newPath;
};

const handleFormChange = (newFormData) => {
  formData.value = newFormData; // 更新本地表单数据
  sendEditActionMessage(newFormData);
};

const sendEditActionMessage = (newFormData) => {
  const editAction = {
    type: "update",
    formId: route.query.id,
    value: newFormData,
  };

  const message = {
    type: "EDIT_ACTION",
    formId: route.query.id,
    editAction: JSON.stringify(editAction),
  };

  socket.send(JSON.stringify(message));
};

const toggleMemberManage = () => {
  showMemberManage.value = !showMemberManage.value;
};

onMounted(() => {
  const id = route.query.id;
  if (id) {
    fetchFormList(id);
    initializeWebSocket(id);

    // 监听页面卸载事件
    window.addEventListener("beforeunload", handleBeforeUnload);
  } else {
    ElMessage.error("缺少必要的参数 id");
  }
});

onBeforeUnmount(() => {
  // 卸载时移除事件监听
  window.removeEventListener("beforeunload", handleBeforeUnload);

  // 关闭 WebSocket 并发送退出编辑消息
  if (socket && socket.readyState === WebSocket.OPEN) {
    sendExitEditMessage();
    socket.close();
  }
});

// 处理浏览器页面卸载前的事件
const handleBeforeUnload = (event) => {
  // 发送退出编辑消息
  if (socket && socket.readyState === WebSocket.OPEN) {
    sendExitEditMessage();
    socket.close();
  }

  // 阻止浏览器默认行为并显示退出确认提示
  event.preventDefault();
  event.returnValue = "";
};

const initializeWebSocket = (formId) => {
  const userInfo = localStorage.getItem("userInfo");
  if (!userInfo) {
    console.error("UserInfo 未找到");
    return;
  }

  const parsedUserInfo = JSON.parse(userInfo);
  const token = parsedUserInfo.token;

  if (!token) {
    console.error("Token 未找到");
    return;
  }

  const wsUrl = `ws://localhost:8080/ws/form/edit/${formId}?token=${token}`;
  socket = new WebSocket(wsUrl);

  socket.onopen = () => {
    console.log("WebSocket 已连接");
    sendEnterEditMessage();
  };

  socket.onmessage = (event) => {
    const message = JSON.parse(event.data);
    handleWebSocketMessage(message);
  };

  socket.onclose = () => {
    console.log("WebSocket 连接关闭");
  };

  socket.onerror = (error) => {
    console.error("WebSocket 错误:", error);
  };
};

const sendEnterEditMessage = () => {
  const message = {
    type: "ENTER_EDIT",
    formId: route.query.id,
    userId: "currentUserId", // 当前用户的ID
    userName: "currentUserName", // 当前用户的名字
  };
  socket.send(JSON.stringify(message));
};

const handleWebSocketMessage = (message) => {
  if (message.type === "ENTER_EDIT") {
    editStatusMessage.value = `${message.message}`;

    // 从 localStorage 中获取 userInfo
    const userInfo = localStorage.getItem("userInfo");
    if (userInfo) {
      const parsedUserInfo = JSON.parse(userInfo);
      const storedUserId = parsedUserInfo.userId;
      // 比较 message.userId 和 storedUserId
      if (String(message.userId) === String(storedUserId)) {
        isFormDisabled.value = false;
      } else {
        isFormDisabled.value = true;
      }
    } else {
      isFormDisabled.value = true;  // 如果没有 userInfo，禁用编辑
    }
  } else if (message.type === "EXIT_EDIT") {
    editStatusMessage.value = `${message.message}`;
    isFormDisabled.value = false; // 恢复表单编辑
  } else if (message.type === "EDIT_ACTION") {
    const editAction = JSON.parse(message.editAction);

    loadFormData(route.query.id);
    updateFormBasedOnEditAction(editAction);
  }
};


const updateFormBasedOnEditAction = (editAction) => {
  if (editAction.type === "add") {
    formData.value[editAction.field] = editAction.value;
  } else if (editAction.type === "remove") {
    delete formData.value[editAction.field];
  } else if (editAction.type === "update") {
    formData.value[editAction.field] = editAction.value;
  }
};

const sendExitEditMessage = () => {
  const message = {
    type: "EXIT_EDIT",
    formId: route.query.id,
    userId: "currentUserId", // 当前用户的ID
    userName: "currentUserName", // 当前用户的名字
  };
  socket.send(JSON.stringify(message));
};
</script>

<style scoped>
.edit-status-message {
  background-color: #fdf6ec;
  color: #e6a23c;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 2vh;
}
</style>
